package com.mobile.mobilehardware.sdcard;

import com.mobile.mobilehardware.utils.Logs;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.utils.zson.ZSONObject;

import java.io.File;


/**
 * @author guxiaonian
 */
class SDCardInfo {

    private static final String TAG = SDCardInfo.class.getSimpleName();

    static ZSONObject getSdCard(Context context) {
        SDCardBean sdCardBean = new SDCardBean();
        try {
            sdCardBean.setSDCardEnable(isSDCardEnableByEnvironment(context));
            sdCardBean.setsDCardPath(getSDCardPathByEnvironment(context));
        } catch (Exception e) {
            Logs.e(TAG, e.toString());
        }
        return sdCardBean.toJSONObject();
    }

    private static String getSDCardPathByEnvironment(Context context) {
        File path = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        int subpathindex = path.getAbsolutePath().indexOf("/emulated/0/");
        if (subpathindex > 0) {
            subpathindex += "/emulated/0/".length();
        }
        if (subpathindex >= 0 && path.getAbsolutePath().contains("/storage/")) {
            return path.getAbsolutePath().substring(0, subpathindex);
        }
        return null;
    }


    private static boolean isSDCardEnableByEnvironment(Context context) {
        File path = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        int subpathindex = path.getAbsolutePath().indexOf("/emulated/0/");
        if (subpathindex > 0) {
            subpathindex += "/emulated/0/".length();
        }
        if (subpathindex >= 0 && path.getAbsolutePath().contains("/storage/")) {
            return true;
        }
        return false;
    }
}
